@page "/settings"
@inject ILocalStorageService LocalStorage
@inject ILogService LogService
@inject HttpClient HttpClient

<PageTitle>系统设置</PageTitle>

<div>
    <Title Level="2">系统设置</Title>
    
    <Card Title="AI模型配置" Style="margin-top: 16px;">
        <Form Model="apiConfig" 
              LabelCol="new ColLayoutParam { Span = 4 }" 
              WrapperCol="new ColLayoutParam { Span = 20 }"
              OnFinish="SaveApiConfig">
            <FormItem Label="模型服务商">
                <Select @bind-Value="apiConfig.Provider"
                        Placeholder="请选择模型服务商"
                        TItemValue="string"
                        TItem="string"
                        OnSelectedItemChanged="OnProviderChanged">
                    <SelectOptions>
                        @foreach (var provider in ModelProviders.GetAll())
                        {
                            <SelectOption Value="@provider" Label="@provider" TItemValue="string" TItem="string" />
                        }
                    </SelectOptions>
                </Select>
                @if (providerInfo != null && !string.IsNullOrEmpty(providerInfo.DocumentUrl))
                {
                    <div style="margin-top: 4px;">
                        <a href="@providerInfo.DocumentUrl" target="_blank">
                            <Icon Type="link" /> 查看官方文档
                        </a>
                    </div>
                }
            </FormItem>
            
            <FormItem Label="API Key">
                <InputPassword @bind-Value="apiConfig.ApiKey" 
                               Placeholder="请输入API Key"
                               VisibilityToggle />
                @if (providerInfo != null && !string.IsNullOrEmpty(providerInfo.ApiKeyHint))
                {
                    <div style="color: #666; font-size: 12px; margin-top: 4px;">
                        💡 @providerInfo.ApiKeyHint
                    </div>
                }
            </FormItem>
            
            <FormItem Label="模型名称">
                <Input @bind-Value="apiConfig.ModelName" 
                       Placeholder="请输入模型名称" />
                @if (providerInfo != null && !string.IsNullOrEmpty(providerInfo.ModelNameHint))
                {
                    <div style="color: #666; font-size: 12px; margin-top: 4px;">
                        💡 @providerInfo.ModelNameHint
                    </div>
                }
            </FormItem>
            
            <FormItem Label="API地址">
                <Input @bind-Value="apiConfig.BaseUrl" 
                       Placeholder="@(providerInfo?.BaseUrl ?? "请输入API基础地址")" />
                <div style="color: #666; font-size: 12px; margin-top: 4px;">
                    留空将使用默认地址: @(providerInfo?.BaseUrl ?? "")
                </div>
            </FormItem>
            
            @if (apiConfig.LastTestTime.HasValue)
            {
                <FormItem Label="测试状态">
                    <div>
                        <Tag Color="@(apiConfig.IsTestSuccess ? "green" : "red")">
                            @(apiConfig.IsTestSuccess ? "连接成功" : "连接失败")
                        </Tag>
                        <Text Type="secondary" Style="margin-left: 8px;">
                            最后测试: @apiConfig.LastTestTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                        </Text>
                    </div>
                </FormItem>
            }
            
            <FormItem WrapperCol="new ColLayoutParam { Offset = 4, Span = 20 }">
                <Space>
                    <SpaceItem>
                        <Button Type="@ButtonType.Primary" 
                                HtmlType="submit" 
                                Loading="saving">
                            保存配置
                        </Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Button OnClick="TestConnection" 
                                Loading="testing"
                                Disabled="string.IsNullOrEmpty(apiConfig.ApiKey)">
                            测试连接
                        </Button>
                    </SpaceItem>
                </Space>
            </FormItem>
        </Form>
    </Card>
    
    <Card Title="系统信息" Style="margin-top: 16px;">
        <Row Gutter="16">
            <Col Span="12">
                <Statistic Title="存储的孩子档案" Value="@childrenCount" />
            </Col>
            <Col Span="12">
                <Statistic Title="生成的试卷数量" Value="@examsCount" />
            </Col>
        </Row>
        <Row Gutter="16" Style="margin-top: 16px;">
            <Col Span="12">
                <Statistic Title="系统日志条数" Value="@logsCount" />
            </Col>
            <Col Span="12">
                <Statistic Title="数据存储方式" Value="@("本地IndexedDB")" />
            </Col>
        </Row>
    </Card>
    
    <Card Title="数据管理" Style="margin-top: 16px;">
        <Alert Type="@AlertType.Warning" 
               Message="危险操作" 
               Description="以下操作会永久删除数据，请谨慎操作！" 
               ShowIcon="true" />
        <div style="margin-top: 16px;">
            <Space>
                <SpaceItem>
                    <Popconfirm Title="确定要清空所有日志吗？" 
                                OnConfirm="ClearLogs"
                                OkText="确定" 
                                CancelText="取消">
                        <Button Icon="delete">清空日志</Button>
                    </Popconfirm>
                </SpaceItem>
                <SpaceItem>
                    <Button OnClick="ExportData" Icon="download">
                        导出数据
                    </Button>
                </SpaceItem>
                <SpaceItem>
                    <Popconfirm Title="确定要清空所有数据吗？此操作不可恢复！" 
                                OnConfirm="ClearAllData"
                                OkText="确定" 
                                CancelText="取消">
                        <Button Danger Icon="delete">清空所有数据</Button>
                    </Popconfirm>
                </SpaceItem>
            </Space>
        </div>
    </Card>
</div>

@code {
    private ApiConfig apiConfig = new();
    private bool saving = false;
    private bool testing = false;
    private int childrenCount = 0;
    private int examsCount = 0;
    private int logsCount = 0;
    private ProviderInfo? providerInfo;
    
    protected override async Task OnInitializedAsync()
    {
        await LoadSettings();
        await LoadStatistics();
        UpdateProviderInfo();
    }
    
    private async Task LoadSettings()
    {
        try
        {
            var config = await LocalStorage.GetApiConfigAsync();
            apiConfig = config ?? new ApiConfig();
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"加载设置失败: {ex.Message}", "Settings");
        }
    }
    
    private async Task LoadStatistics()
    {
        try
        {
            var children = await LocalStorage.GetChildrenAsync();
            childrenCount = children.Count;
            
            var exams = await LocalStorage.GetExamPapersAsync();
            examsCount = exams.Count;
            
            var logs = await LogService.GetLogsAsync();
            logsCount = logs.Count;
            
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"加载统计信息失败: {ex.Message}", "Settings");
        }
    }
    
    private async Task SaveApiConfig()
    {
        if (string.IsNullOrEmpty(apiConfig.ApiKey))
        {
            // TODO: 显示错误提示
            return;
        }
        
        try
        {
            saving = true;
            await LocalStorage.SaveApiConfigAsync(apiConfig);
            await LogService.LogInfoAsync("保存API配置", "Settings");
            
            // TODO: 显示成功提示
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"保存API配置失败: {ex.Message}", "Settings");
        }
        finally
        {
            saving = false;
        }
    }
    
    private async Task TestConnection()
    {
        try
        {
            testing = true;
            
            // 这里应该实现实际的API测试逻辑
            // 暂时模拟测试
            await Task.Delay(2000);
            
            apiConfig.LastTestTime = DateTime.Now;
            apiConfig.IsTestSuccess = !string.IsNullOrEmpty(apiConfig.ApiKey);
            
            await LocalStorage.SaveApiConfigAsync(apiConfig);
            await LogService.LogInfoAsync($"API连接测试: {(apiConfig.IsTestSuccess ? "成功" : "失败")}", "Settings");
            
            StateHasChanged();
        }
        catch (Exception ex)
        {
            apiConfig.IsTestSuccess = false;
            apiConfig.LastTestTime = DateTime.Now;
            await LogService.LogErrorAsync($"API连接测试失败: {ex.Message}", "Settings");
        }
        finally
        {
            testing = false;
        }
    }
    
    private async Task ClearLogs()
    {
        try
        {
            await LogService.ClearLogsAsync();
            await LogService.LogInfoAsync("清空系统日志", "Settings");
            await LoadStatistics();
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"清空日志失败: {ex.Message}", "Settings");
        }
    }
    
    private async Task ExportData()
    {
        try
        {
            var logs = await LogService.ExportLogsAsync();
            // TODO: 实现数据导出功能
            await LogService.LogInfoAsync("导出系统数据", "Settings");
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"导出数据失败: {ex.Message}", "Settings");
        }
    }
    
    private async Task ClearAllData()
    {
        try
        {
            await LocalStorage.ClearAllAsync();
            await LogService.LogInfoAsync("清空所有数据", "Settings");
            
            // 重新初始化
            apiConfig = new ApiConfig();
            await LoadStatistics();
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"清空数据失败: {ex.Message}", "Settings");
        }
    }
    
    private void OnProviderChanged(string selectedProvider)
    {
        apiConfig.Provider = selectedProvider;
        UpdateProviderInfo();
        
        // 如果切换服务商，清空之前的配置（保留API Key）
        if (providerInfo != null)
        {
            apiConfig.BaseUrl = providerInfo.BaseUrl;
            apiConfig.ModelName = string.Empty;
        }
        
        StateHasChanged();
    }
    
    private void UpdateProviderInfo()
    {
        providerInfo = ModelProviders.GetProviderInfo(apiConfig.Provider);
    }
} 